﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using MeterReader.Models;
using Microsoft.EntityFrameworkCore;

namespace MeterReader.Services.Repositories
{
    public class MeterWriteRepository : IWriteDbRepository
    {
        private readonly MeterDBContext _dbContext;

        public MeterWriteRepository(MeterDBContext dbContext)
        {
            _dbContext = dbContext;
        }

        public async Task WriteDataAsync(TableMeters tableMeters, CancellationToken cancellationToken)
        {
            await _dbContext.TMeters!.AddAsync(tableMeters, cancellationToken);
            await _dbContext.SaveChangesAsync(cancellationToken);
        }

        public IEnumerable<string> GetMeterColumnsFromTMeters()
        {
            return GetDoubleColumnsFromTMeters()
                .OrderBy(col =>
                {
                    // 使用正则表达式提取字符串中的第一个数字
                    var match = Regex.Match(col, @"\d+");
                    if (match.Success)
                    {
                        // 将提取的数字转换为整数
                        return int.Parse(match.Value);
                    }
                    // 如果没有找到数字，则返回一个默认值（这里选择返回 MaxValue，意味着这些项会被排在最后）
                    return int.MaxValue;
                });
        }

        private IEnumerable<string> GetDoubleColumnsFromTMeters()
        {
            // 确保 DbContext 已经初始化
            if (_dbContext.Model == null)
            {
                throw new InvalidOperationException("DbContext has not been initialized.");
            }

            // 查找 TMeters 实体类型
            var tMeterEntityType = _dbContext.Model.FindEntityType(typeof(TableMeters));
            if (tMeterEntityType == null)
            {
                throw new InvalidOperationException("Could not find TMeter entity type.");
            }

            foreach (var property in tMeterEntityType.GetProperties())
            {
                if (property.ClrType == typeof(double) || property.ClrType == typeof(double?))
                {
                    yield return property.Name;
                }
            }
        }

        public IQueryable<TableMeters> SearchHistory(System.Linq.Expressions.Expression<Func<TableMeters, bool>> predicate) => _dbContext.TMeters.Where(predicate);
    }
}
